package com.lego.servlet;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.lego.bean.Goods;
import com.lego.bean.Seller;
import com.lego.service.GoodsService;
import com.lego.service.SellerService;
import com.lego.service.impl.GoodsServiceImpl;
import com.lego.service.impl.SellerServiceImpl;

@MultipartConfig
@WebServlet("/addGoods.do")
public class AddGoodsServlet extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		SellerService ss = new SellerServiceImpl();
		GoodsService gs = new GoodsServiceImpl();
		String brandName = request.getParameter("sellerName");
		String goodsName = request.getParameter("goodsName");
		String description = request.getParameter("description");
		String goodsType = request.getParameter("goodsType");
		Double price = 0.0;
		int quantity = 0;
		try {
			quantity = Integer.parseInt(request.getParameter("quantity"));
		} catch (Exception e) {
			System.out.println("没有传入数量");
		}
		try {
			price = Double.parseDouble(request.getParameter("price"));
		} catch (Exception e) {
			System.out.println("没有传入价格");
		}
		Part part = request.getPart("goodsImg");
		String goodsImg = "";
		if(part != null && part.getSize() > 0){
			if(part.getContentType().contains("image")) {
				String fileName = UUID.randomUUID()+"_"+part.getSubmittedFileName();
				String savePath = "c:/legoImage/goodsImg/"+fileName;
				goodsImg = "/lego/goodsImg/"+fileName;
				part.write(savePath);
			}
		}
		Seller seller = ss.selectBySellerName(brandName);
		int sellerId = seller.getSellerId();
		Goods goods = new Goods();
		goods.setDescription(description);
		goods.setGoodsImg(goodsImg);
		goods.setGoodsName(goodsName);
		goods.setPrice(price);
		goods.setGoodsType(goodsType);
		goods.setQuantity(quantity);
		goods.setSellerId(sellerId);
		int row = gs.addGoods(goods);
		response.sendRedirect("/lego/admin.jsp");
	}
}
